package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealGroup;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealGroupService;
import com.itheima.service.SetmealService;
import com.itheima.utils.FileUtils;
import com.itheima.vo.CheckGroupVo;
import com.itheima.vo.SetmealVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealGroupService setmealGroupService;

    @Resource
    private CheckGroupService checkGroupService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private CheckItemService checkItemService;

    //查找全部数据
    @Override
    public List<Setmeal> findAll() {

        //拼接is_delete =0;
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag","0");

        return this.list(queryWrapper);
    }

    //新增or编辑
    @Override
    @Transactional
    public void addOrUpdate(SetmealDto setmealDto) {
        //保存新增or编辑套餐
        this.saveOrUpdate(setmealDto.getSetmeal());

        //从file：set集合中移除图片

        //如果为点击确定按钮 提交图片 则从缓存中移除此图片
        if(setmealDto.getSetmeal().getImg()!=null){
            redisTemplate.opsForSet().remove("file:allset",setmealDto.getSetmeal().getImg());
        }

        //每次往中间插入数据的时候 根据该套餐id删除中间表信息
        setmealGroupService.deleteBySetmealId(setmealDto.getSetmeal().getId());

        //向中间表插入数据
        ArrayList<SetmealGroup> list = new ArrayList<>();
        for (Long groupId :setmealDto.getGroupIds()) {
            SetmealGroup setmealGroup = new SetmealGroup();
            //套餐id
            setmealGroup.setGroupId(groupId);
            setmealGroup.setSetmealId(setmealDto.getSetmeal().getId());
            list.add(setmealGroup);
        }

        //使用list链表 批量插入数据
        setmealGroupService.saveBatch(list);

    }

    //根据id逻辑删除
    @Override
    public void deleteById(Long id) {

        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setDeleteFlag(1);

        this.updateById(setmeal);
    }

    //分页查询
    @Override
    public PageResult findByPage(QueryPageBean pageBean) {

        //首先过滤is_delete=0;
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag","0");

        //是否存在条件查询
        if (pageBean.getQueryString()!=null && "".equals(pageBean.getQueryString().trim())==false){
            //拼接查询条件
            queryWrapper.and(setmealQueryWrapper ->
                    setmealQueryWrapper.like("code",pageBean.getQueryString()).or().like("name",pageBean.getQueryString())
                    .or().like("help_code",pageBean.getQueryString())
            );
        }
        //分页  当前页  页面尺寸
        Page<Setmeal> setmealPage = new Page<>(pageBean.getCurrentPage(), pageBean.getPageSize());

        Page<Setmeal> page = this.page(setmealPage, queryWrapper);

        return new PageResult(page.getTotal(),page.getRecords());
    }



    @Override
    public void clearOssObject() {
        //取出file：allset集合元素
        Set<Object> allset = redisTemplate.opsForSet().members("file:allset");
        //如果集合不为空，遍历集合 获取文件名
        if (allset!=null){
            for (Object path:allset){
                //拼接为key值
                String fileKey = "file:"+path;
                //如果缓存中不存在该key值
                if (redisTemplate.hasKey(fileKey)==false){
                    //从oss删除
                    FileUtils.delete((String)path);
                    //从file：allset删除
                    redisTemplate.opsForSet().remove("file:allset",path);
                }
            }
        }
    }

    //通过套餐id查询检查组信息
    @Override
    public SetmealVo findSetmealDetail(Long setmealId) {
        //查询套餐基本信息
/*        SetmealVo setmealVo = new SetmealVo();
        Setmeal setmeal = this.getById(setmealId);
        BeanUtils.copyProperties(setmeal,setmealVo);*/
        SetmealVo setmealVo = this.baseMapper.findById(setmealId);
        //通过套餐查询检查组列表
        List<CheckGroupVo> groups=checkGroupService.findBySetmealId(setmealId);
        setmealVo.setCheckGroupVo(groups);
        //通过检查组查询检查项列表
        if (groups!=null){
            for (CheckGroupVo group : groups) {
                group.setCheckItems(checkItemService.findBygroupId(group.getId()));
            }
        }

        return setmealVo;
    }


}
